using System;
using System.Configuration;
using System.IO;
using ManticLabs.Data;

namespace ManticLabs.Common
{
	public class Logger
	{
	
		//private static string logPath = "";
		//private static int configLogLevel = 1;

		public Logger()
		{

		}

        private static string logPath
        {
            get {
                string sPath = "";
                if (ConfigurationManager.AppSettings["LogPath"] != null)
                    if (ConfigurationManager.AppSettings["LogPath"] !=null)
                        sPath = ConfigurationManager.AppSettings["LogPath"].ToString();

                try
			    {
				    Directory.CreateDirectory(sPath); 
			    }
			    catch (Exception ex)
			    {
                    //Logger.Log(ex.Source + " : " + ex.Message, LogLevelType.SQLERROR) ; 
			    }
                return sPath;
            }
        }


        private static int configLogLevel
        {
            get
            {
                int rtnVal = 1;
                int.TryParse(ConfigurationManager.AppSettings["LogLevel"].ToString(), out rtnVal);
                return rtnVal;
            }
        }

		public static void Log(string msg, LogLevelType logLevel)
		{
			try
			{
				Write(DateTime.Now.ToString("MM:dd:yyyy hh:mm:ss") + '\t' + msg, logLevel);
			}
			catch
			{
			}
		}

		private static void Write(string msg, LogLevelType logLevel)
		{
            string fileName;
            TextWriter output;
            string levelString = "";

			if ((int )logLevel < configLogLevel)
				return;

			switch(logLevel)
			{
				case LogLevelType.DEBUG:
					levelString = "DEBUG: ";
					break;
				case LogLevelType.INFO:
					levelString = "INFO: ";
					break;
				case LogLevelType.ERROR:
					levelString = "ERROR: ";
					break;
				case LogLevelType.SQLERROR:
					levelString = "SQL ERROR: ";
					break;
				case LogLevelType.SQLINTEGRITYERROR:
					levelString = "SQL INTEGRITY ERROR: ";
					break;
			}

			try
			{
                
				fileName = logPath +  "ManticLabs_App_Log_" + DateTime.Now.ToString("MMddyyyy") + ".txt";

				output = File.AppendText(fileName);

				output.WriteLine(levelString + '\t' + msg);

				output.Close();
			}
			catch(Exception ex)
			{
				throw(ex);
			}
		}
	}
}
